<?php

/**
 * This is the model class for table "{{product}}".
 *
 * The followings are the available columns in table '{{product}}':
 * @property integer $id
 * @property integer $categoryID
 * @property string $size
 * @property integer $sort
 * @property integer $createddate
 * @property integer $modifieddate
 * @property integer $enabled
 * @property integer $deleted
 *
 * The followings are the available model relations:
 * @property Category $category
 * @property ProductFile[] $productFiles
 * @property ProductLang[] $productLangs
 */
class Product extends CActiveRecord
{
  public $name;
  public $name2;
  public $price;
  public $price2;
  public $color;
  public $color2;
  public $languageID;
  
  public $description;
  public $description2;
  public $detail;
  public $detail2;
  
  public $image;
  public $thumbnails = array(
    array('70','60'),
    array('125', '120'),
    array('250', '240'),
    array('520', '400')
  );
  /**
   * Returns the static model of the specified AR class.
   * @param string $className active record class name.
   * @return Product the static model class
   */
  public static function model($className = __CLASS__)
  {
    return parent::model($className);
  }
  
  /**
   * @return string the associated database table name
   */
  public function tableName()
  {
    return '{{product}}';
  }
  
  /**
   * @return array validation rules for model attributes.
   */
  public function rules()
  {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
      array(
        'name, categoryID',
        'required'
      ),
      array(
        'categoryID, createddate, modifieddate, enabled, deleted',
        'numerical',
        'integerOnly' => true
      )
      // The following rule is used by search().
      // Please remove those attributes that should not be searched.
      //array('id, categoryID, price, sizeID, colorID, sort, fileID, createddate, modifieddate, enabled, deleted', 'safe', 'on'=>'search'),
    );
  }
  
  /**
   * @return array relational rules.
   */
  public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
      //'color' => array(self::BELONGS_TO, 'Color', 'colorID'),
      'category' => array(
        self::BELONGS_TO,
        'Category',
        'categoryID'
      ),
      'productFiles' => array(
        self::HAS_MANY,
        'ProductFile',
        'productID'
      ),
      //'size' => array(self::BELONGS_TO, 'Size', 'sizeID'),
      'productLangs' => array(
        self::HAS_MANY,
        'ProductLang',
        'productID'
      )
    );
  }
  
  /**
   * @return array customized attribute labels (name=>label)
   */
  public function attributeLabels()
  {
    return array(
      'id' => 'ID',
      'name' => Yii::t('default', 'Product'),
      'description' => Yii::t('default', 'Description'),
    	'detail' => Yii::t('default', 'Detail'),
      'categoryID' => Yii::t('default', 'Category'),
      'price' => Yii::t('default', 'Price'),
      'size' => Yii::t('default', 'Size'),
      'color' => Yii::t('default', 'Color'),
      'sort' => 'Sort',
      'fileID' => 'File',
      'createddate' => Yii::t('default', 'Createddate'),
      'modifieddate' => Yii::t('default', 'Modifieddate'),
      'enabled' => Yii::t('default', 'Enabled'),
      'deleted' => 'Deleted'
    );
  }
  
  protected function beforeSave()
  {
    if ($this->isNewRecord) {
      $this->createddate = time();
    }
    $this->modifieddate = time();
    return parent::beforeSave();
  }
  
  public function getProducts($catID = '', $except = '', $search = '')
  {
    if ($catID == '') {
      $condition = '';
      if ($search != '') {
        $condition = "(t.size LIKE '%$search%' OR l.name LIKE '%$search%' OR l.color LIKE '%$search%' OR 
        	l.price LIKE '%$search%' OR l.description LIKE '%$search%' OR l.detail LIKE '%$search%') AND "; 
      }
      $products = Yii::app()->db->createCommand()
        ->select('t.id, l.name, l.description, l.price')
        ->from('tbl_product as t')
        ->join('tbl_product_lang as l', 'l.productID = t.id')
        ->where($condition . 't.enabled = 1 AND t.deleted = 0 AND l.languageID="' . Yii::app()->session['language'] . '"')
        ->order('t.createddate DESC')
        ->queryAll();
    }
    else {
      $products = Yii::app()->db->createCommand()
        ->select('t.id, l.name, l.description, l.price')
        ->from('tbl_product as t')
        ->join('tbl_product_lang as l', 'l.productID = t.id')
        ->join('tbl_category as cat', 'cat.id = t.categoryID')
        ->where('t.enabled = 1 AND t.deleted = 0 AND l.languageID="' . Yii::app()->session['language'] . '" AND cat.deleted = 0 AND md5(t.categoryID) = "' . $catID . '"')
        ->order('t.createddate DESC')
        ->queryAll();
        
      if ($except != '') {
        $products = Yii::app()->db->createCommand()
          ->select('t.id, l.name, l.description, l.price')
          ->from('tbl_product as t')
          ->join('tbl_product_lang as l', 'l.productID = t.id')
          ->join('tbl_category as cat', 'cat.id = t.categoryID')
          ->where('t.enabled = 1 AND t.deleted = 0 AND t.id<>' . $except . ' AND l.languageID="' . Yii::app()->session['language'] . '" AND cat.deleted = 0 AND md5(t.categoryID) = "' . $catID . '"')
          ->order('t.createddate DESC')
          ->queryAll();
      }
    }
    return $products;
  }
  
  public function getProductFile($productID, $w, $h)
  {
    $product_files = ProductFile::model()->findByAttributes(array('productID' =>$productID));
    $image = 'no_image.jpg';
    if (!empty($product_files)) {
      $file = $product_files->file;
      if (!empty($file) && file_exists(Yii::app()->basePath . "/../upload/product/thumbs_$w"."x"."$h/" . $file->filesaved)) {
        $image = $file->filesaved;
      }
    }
    return $image;
  }
  
  public function getProductFiles($productID, $except = '')
  {
    $image         = array();
    $product_files  = ProductFile::model()->findAllByAttributes(array(
      'productID' => $productID
    ));
    if (!empty($product_files)) {
      foreach ($product_files as $product_file) {
        $image[] = File::model()->getFile($product_file->fileID);
      }
    }
    return $image;
  }
  
  public function getProductImage($productID, $w, $h)
  {
    $linkfile = $this->getProductFile($productID, $w, $h);
    $image    = CHtml::image(Yii::app()->baseUrl . "/upload/product/thumbs_$w" . "x" . "$h/$linkfile");
    return $image;
  }
  /**
   * Retrieves a list of models based on the current search/filter conditions.
   * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
   */
  public function search()
  {
    $criteria           = new CDbCriteria;
    $criteria->together = true;
    
    $criteria->select    = 't.*, l.name, l.price, l.color, l.description, l.detail';
    $criteria->join      = 'JOIN tbl_product_lang l ON t.id=l.productID 
    	JOIN tbl_category cat ON cat.id=t.categoryID LEFT JOIN tbl_category_lang cat_l ON cat.id = cat_l.categoryID AND cat_l.languageID="' . Yii::app()->session['language'] . '"';
    //JOIN tbl_color c ON c.id = t.colorID LEFT JOIN tbl_color_lang c_l ON c.id = c_l.colorID AND c_l.languageID="' . Yii::app()->session['language'] . '" 
    //JOIN tbl_size s ON s.id = t.sizeID';
    $criteria->condition = 't.deleted=0 AND l.languageID="' . Yii::app()->session['language'] . '"';
    $criteria->compare('t.id', $this->id);
    $criteria->compare('l.name', $this->name, true);
    $criteria->compare('cat_l.name', $this->categoryID, true);
    $criteria->compare('l.price', $this->price, true);
    $criteria->compare('l.color', $this->color, true);
    $criteria->compare('t.size', $this->size, true);
    $criteria->compare('t.enabled', $this->enabled);
    
    return new CActiveDataProvider($this, array(
      'criteria' => $criteria,
      'sort' => array(
        'attributes' => array(
          'name' => array(
            'asc' => 'l.name',
            'desc' => 'l.name DESC'
          ),
          'description' => array(
            'asc' => 'l.description',
            'desc' => 'l.description DESC'
          ),
          'price' => array(
            'asc' => 'l.price',
            'desc' => 'l.price DESC'
          ),
          'color' => array(
            'asc' => 'l.color',
            'desc' => 'l.color DESC'
          ),
          '*'
        )
      ),
      'pagination' => array(
        'pageSize' => Yii::app()->user->getState('pageSize', 10)
      )
    ));
  }
}
?>